package com.ruoyi.ai.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
@Slf4j
public class HttpClientService {
    private final CloseableHttpClient httpClient;

    public HttpClientService(CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public String sendGet(String url, Map<String, String> headers) {
        HttpGet request = new HttpGet(url);
        String result = null;
        if (headers != null) {
            headers.forEach(request::addHeader);
        }
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException | ParseException e) {
            log.error("sendGetRequest error", e);
        }
        return result;
    }

    /**
     * 发送 post 请求
     *
     * @param url         请求地址
     * @param jsonPayload 请求体
     * @return 请求结果
     */
    public String sendPostRequest(String url, String jsonPayload, Map<String, String> headers) {
        HttpPost request = new HttpPost(url);
        log.info("sendPostRequest url: {}, jsonPayload: {}", url, jsonPayload);
        if (headers != null) {
            headers.forEach(request::addHeader);
        }
        String result = null;
        request.setEntity(new StringEntity(jsonPayload, ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            log.info("sendPostRequest result: {}", result);
        } catch (IOException | ParseException e) {
            log.error("sendPostRequest error", e);
        }
        return result;
    }
}
